package com.cmz.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring 上下文工具
 * @author cmz
 */
@Slf4j
@Component
@Lazy(false)
public class SpringUtils implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        updateApplicationContext(applicationContext);
    }

    private static void updateApplicationContext(ApplicationContext applicationContext) {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> Map<String, T> getBeans(Class<T> beanClass) {
        return applicationContext.getBeansOfType(beanClass);
    }

    public static boolean hasBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    public static <T> boolean hasBean(Class<T> beanClass) {
        return hasBean(StringUtils.uncapitalize(beanClass.getSimpleName()));
    }

    public static void clear() {
        if (log.isDebugEnabled()) {
            log.debug("清除SpringUtils中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    @Override
    public void destroy() {
        clear();
    }

    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }
}
